package tcp

import (
	"fmt"
	"log"
	"net/http"
	"strings"
	"encoding/json"
	"github.com/gorilla/websocket"
	"bufio"
	"os"
)
// 在线用户结构
type User struct {
	ID       string
	Username string
	Group      string
	Conn     *websocket.Conn
}
// 分组结构体
type Group struct {
	Name    string
	Members map[string]bool // 以用户ID为键的成员列表
}
// 分组列表
var groups map[string]Group
// 在线用户列表
var onlineUsers map[string]User
// 升级HTTP连接为WebSocket连接
var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}
// 处理点对点消息
func handlePrivateMessage(user User, message string) {
	// 解析消息，获取目标用户标识
	// 假设消息格式为：To:目标用户标识;Content:消息内容
	parts := strings.Split(message, ";")
	if len(parts) != 2 {
		log.Printf("Invalid private message format from user: %s", user.Username)
		return
	}
	toParts := strings.Split(parts[0], ":")
	if len(toParts) != 2 || toParts[0] != "To" {
		log.Printf("Invalid private message format from user: %s", user.Username)
		return
	}
	targetUserID := strings.TrimSpace(toParts[1])

	// 检查目标用户是否在线
	targetUser, ok := onlineUsers[targetUserID]
	if ok {
		// 目标用户在线，将消息发送给目标用户
		err := targetUser.Conn.WriteMessage(websocket.TextMessage, []byte(parts[1]))
		if err != nil {
			log.Printf("Error sending private message to user: %s", targetUser.Username)
		}
	} else {
		// 目标用户不在线，可以进行相应处理，比如存储离线消息等
		log.Printf("User %s is offline. Storing offline message: %s", targetUserID, parts[1])
	}
}
func handleWebSocketConnection(w http.ResponseWriter, r *http.Request) {
	// 升级HTTP连接为WebSocket连接
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Printf("Error upgrading connection to WebSocket: %v", err)
		return
	}
	query := r.URL.Query()
    uid := query["uid"][0]
	Groupsname := query["group"][0]
	fmt.Println(uid);
	// uid := r.Form["id"]
	// 进行用户认证，假设这里会返回用户信息，包括唯一标识和用户名
	user := User{
		ID:       uid,
		Username: "Alice",
		Conn:     conn,
		Group:     Groupsname,
	}
// 检查用户所属的分组是否存在，如果不存在则创建该分组
group, ok := groups[user.Group]
fmt.Println("err");
if !ok {
	group = Group{
		Name:    user.Group,
		Members: make(map[string]bool),
	}
	// fmt.Println(user.Members);
	groups[user.Group] = group
}
// 将用户添加到分组的成员列表中
group.Members[user.ID] = true
	// 将用户添加到在线用户列表
	onlineUsers[user.ID] = user
	// 监听WebSocket消息
	for {
		// 读取WebSocket消息
		_, message, err := conn.ReadMessage()
		if err != nil {
			// 处理错误
			log.Printf("Error reading message from user %s: %s", user.Username, err.Error())
			break
		}
		// 处理点对点消息
		handlePrivateMessage(user, strings.TrimSpace(string(message)))
	}
	// 用户断开连接，从在线用户列表中移除用户
	delete(onlineUsers, user.ID)
}
func handleonlineUsers(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	  json.NewEncoder(w).Encode(onlineUsers)
}
func haddelete(w http.ResponseWriter, r *http.Request) {
	query := r.URL.Query()
    uid := query["uid"][0]
	delete(onlineUsers, uid)
}
// 通知全部
func broadcastMessage(w http.ResponseWriter, r *http.Request) {
	query := r.URL.Query()
    message := query["message"][0]
	for _, user := range onlineUsers {
		err := user.Conn.WriteMessage(websocket.TextMessage, []byte(message))
		if err != nil {
			log.Printf("Error broadcasting message to user: %s", user.Username)
		}
	}
}

// 分组通知
func handleGroupMessage(w http.ResponseWriter, r *http.Request) {
	query := r.URL.Query()
    message := query["message"][0]
	groupname := query["groups"][0]
	for memberID := range groups[groupname].Members {
		member, ok := onlineUsers[memberID]
		if !ok {
			log.Printf("User %s is offline. Storing offline group message: %s", memberID, message)
			continue
		}

		err := member.Conn.WriteMessage(websocket.TextMessage, []byte(message))
		if err != nil {
			log.Printf("Error sending group message to user: %s", member.Username)
		}
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(onlineUsers)
}

func Run() {
	fmt.Println("输入你的端口号")
	reader := bufio.NewReader(os.Stdin)
	txt, _ := reader.ReadString('\n')
	// 初始化在线用户列表
	onlineUsers = make(map[string]User)
	// 初始化分组
	groups = make(map[string]Group)
	fmt.Println(groups)
	port := strings.TrimSpace(txt)

 	// 设置WebSocket处理函数
	http.HandleFunc("/ws", handleWebSocketConnection)
	http.HandleFunc("/online", handleonlineUsers)
	http.HandleFunc("/delete", haddelete)
	http.HandleFunc("/sendsll", broadcastMessage)
	http.HandleFunc("/sendgroup", handleGroupMessage)
	fmt.Println("链接服务 ws://localhost:"+port+"/ws?uid=用户标识&group=分组名称")
	fmt.Println("查询全部在线用户 http://localhost:"+port+"/online")
	fmt.Println("通知全部 http://localhost:"+port+"/sendsll?message=内容")
	fmt.Println("通知全部 http://localhost:"+port+"/sendgroup?message=%E9%80%9A%E7%9F%A5%E4%B8%8B%E5%8D%88%E4%B8%A4%E7%82%B9%E5%B9%B2%E5%98%9B343434343&groups=one")

	
	// handleGroupMessage

	fmt.Printf("端口号%s\n", string(txt))
	// 启动Web服务器，监听指定的地址和端口

	err := http.ListenAndServe(":"+port, nil)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Server started on localhost:port")
}